using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Data;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.ComponentModel;
using System.Collections.Specialized;

namespace c3o.Framework.Web
{
    public class UKNovaReader : DataTable
    {
        public string _Login;
        public string _Password;
		public string TorrentPath = "Torrents";

        public SiteReader sr = new SiteReader();
        public bool isLoggedIn = false;

        public UKNovaReader() {}

        public UKNovaReader(string Login, string Password)
        {
            this.Init();
            this._Login = Login;
            this._Password = Password;
        }

        protected void Init()
        {
            this.Columns.Add("name");
            this.Columns.Add("url");
        }
       
        public virtual void Login(string login, string password)
        {
            string loginUrl = "http://www.uknova.com/takelogin.php";
            string postData = "username={0}&password={1}";

            // extract the viewstate value and build out POST data
            postData = String.Format(postData, login, password);

            sr.PostPage(loginUrl, postData);
        }


        /// <summary>
        /// Read page from uknova torrent list start ( page=0 )
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public virtual void GetPage(int page, string SearchString)
        {
            // Login the first time
            if (!this.isLoggedIn)
            {
                this.Login(this._Login, this._Password);
                this.isLoggedIn = true;
            }

            string url = @"http://www.uknova.com/browse.php?page=" + page.ToString();

            //string category = @"?c103=1&c17=1&c105=1&c50=1&c210=1&c5=1&c7=1&c104=1&c9=1&c101=1&c1=1&c4=1&c109=1&c1001=1&c1005=1&c200=1&c1000=1&c102=1&c12=1&c1006=1&c106=1&c19=1&c25=1&c100=1&c6=1";

            if (SearchString != null && SearchString.Length > 0)
            {
                url += "&search=" + SearchString;
            }
            
            string source = this.sr.ReadPage(url);

            if (source != null && source.Length > 0)
            {
                // Find start and end points
                int start = source.IndexOf(@"Name</td>");
                int end = source.IndexOf(@"<p", start);

                // Extract section
                source = source.Substring(start, end - start);

                string pattern = @"noscript><b>(?<name>.*)</b>\n.*download\.php(?<url>.*)torrent";

                // Find data 
                MatchCollection mc = Regex.Matches(source, pattern);

                // Clear table
                this.Clear();

                // Create table row for each match
                foreach (Match m in mc)
                {
                    DataRow row = this.NewRow();
                    row["name"] = m.Groups["name"].Value;
                    row["url"] = @"http://www.uknova.com/download.php" + m.Groups["url"].Value + "torrent";
                    this.Rows.Add(row);
                }
            }
        }


        /// <summary>
        /// Read page from uknova torrent list start ( page=0 )
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public virtual StringDictionary GetProfile(string UserID)
        {
            StringDictionary sd = new StringDictionary();

            // Login the first time
            if (!this.isLoggedIn)
            {
                this.Login(this._Login, this._Password);
                this.isLoggedIn = true;
            }

            string url = @"http://www.uknova.com/userdetails.php";

            string source = this.sr.ReadPage(url + "?id=" + UserID);

            if (source != null && source.Length > 0)
            {
                // Find start and end points
                int start = source.IndexOf(@"<!-- /////////// here we go, with the cats //////////// -->");
                int end = source.IndexOf(@"</html>", start);

                // Extract section
                source = source.Substring(start, end - start);

                // Find data 
                string pattern = @"<tr><td class=rowhead>Uploaded</td><td align=left>(?<uploaded>.*)</td></tr>";
                Match m = Regex.Match(source, pattern);
                sd.Add("Up", m.Groups["uploaded"].Value.Replace(" ", ""));

                pattern = @"<tr><td class=rowhead>Downloaded</td><td align=left>(?<downloaded>.*)</td></tr>";
                m = Regex.Match(source, pattern);
                sd.Add("Down", m.Groups["downloaded"].Value.Replace(" ", ""));

                pattern = @">Share ratio</td><td align=left valign=center style='padding-top: 1px; padding-bottom: 0px'><table border=0 cellspacing=0 cellpadding=0><tr><td class=embedded><font color=#......>(?<ratio>.*)</font>";
                m = Regex.Match(source, pattern);
                sd.Add("Ratio", m.Groups["ratio"].Value.Replace(" ", ""));
            }

            return sd;
        }


        public void DownloadTorrent(string url)
        {
			int i = 1;
			if (url != null && url.Length > 0)
			{
				if (!System.IO.Directory.Exists(this.TorrentPath)) System.IO.Directory.CreateDirectory(this.TorrentPath);
				
				// Find file name
				string FileName = this.TorrentPath + @"\temp" + i.ToString() + ".torrent";
				while (System.IO.File.Exists(FileName))
				{
					i++;
					FileName = this.TorrentPath + @"\temp" + i.ToString() + ".torrent";
				}				

				// Save Torrent file to disk
				this.sr.Download(url, FileName);

				// Launch client
				System.Diagnostics.Process.Start(FileName);
			}
		}
    }
}
